//
//  HJHomeController.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/9/22.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit

private let originalCellId = "HJStatusCellId"
private let retweetedCellId = "HJRetweetedStatusId"
class HJHomeController: HJBaseTableViewController {

    
    
    //创建视图控制器
    lazy var homeViewModel: HJHomeViewModel = HJHomeViewModel()
    
    //实例化上拉刷新小菊花
    lazy var indicatorView: UIActivityIndicatorView = {
       let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        
        return indicatorView
    }()
    
    //懒加载提示条
    lazy var tipLable:UILabel = {
        let lable = UILabel(title: "", textColor: UIColor.white, fontSize: 14)
        
        lable.backgroundColor = UIColor.orange
        
        lable.textAlignment = .center
        lable.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 35)
        lable.isHidden = true
        return lable
    }()
    
    //下拉刷新控件
    let hjRefreshControl = HJRefreshControl()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //界面右侧navigationItem
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
    
        
        if !userLogin {
            visitorView.userInfo(tipText: "关注一些人,快回到这里看看有什么惊喜", imageName: nil)
            return;
        }
  
        //在请求数据之前布置tableView
        setupTableview()
        
        //数据回调
        loadData()

    }

    func loadData() {
        
        homeViewModel.loadData(isPullUp: indicatorView.isAnimating) { (success,count) in
            if !success {
                print("失败")
            }
            print("成功")
           
            self.hjRefreshControl.stopAnimation()
             //刷新数据
            self.tableView.reloadData()
            self.indicatorView.stopAnimating()
            self.startTipLableAnimation(count: count)
        }
    }
    
    
    //当数据刷新成功的时候,tipLable提示刷新了多少条数据
    func startTipLableAnimation(count : Int) {
        
        self.tipLable.text = count == 0 ? "没有;新微薄" : "更新了\(count)条微博"
        self.tipLable.isHidden = false
        
        //先记录之前的y值,等动画结束之后恢复
        let lastY = tipLable.frame.origin.y
        
        UIView.animate(withDuration: 0.5, animations: {
            
            self.tipLable.frame.origin.y = navBarHeight
            
            }) { (_) in
                
                UIView.animate(withDuration: 0.5, delay: 2, options: [], animations: { 
                     self.tipLable.frame.origin.y = lastY
                    }, completion: { (_) in
                        
                        self.tipLable.isHidden = true
                })
        }
    }
    
    
    //界面右侧navigationItem点击的时候进入临时控制器
    func push() {
        let tempVC = HJTempViewController()
      navigationController?.pushViewController(tempVC, animated: true)
    }
    
    
    func setupTableview() {
        //注册原创Cell
        let originalNib = UINib(nibName: "HJStatusCell", bundle: nil)
        tableView.register(originalNib, forCellReuseIdentifier: originalCellId)
        //注册转发cell
        let retweetedNib = UINib(nibName: "HJRetweetedStatus", bundle: nil)
        tableView.register(retweetedNib, forCellReuseIdentifier: retweetedCellId)
        
        //设置行高
        //tableView.rowHeight = 360
        
        //设置分割线
        tableView.separatorStyle = .none
        //设置tableFooterView为小菊花
        tableView.tableFooterView = indicatorView
        
        //数据刷新完之后的提示
        self.tipLable.frame.origin.y = navBarHeight - 35
        self.navigationController?.view.addSubview(tipLable)
        
        //添加监听事件
        hjRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(hjRefreshControl)
        
        //更改控件的顺序
        self.navigationController?.view.insertSubview(tipLable, belowSubview: (self.navigationController?.navigationBar)!)
        
    }
    
   
}





//数据源方法,分类
extension HJHomeController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return homeViewModel.viewModelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewModel = homeViewModel.viewModelArray[indexPath.row]
        
      let cellId = getCellIdWithViewmodel(viewModel: viewModel)
        
       // print(cellId)
        
       let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HJStatusCell
 
        //赋值,相当于调用set方法,此时赋值的为一个视图,需要从视图里取出模型,在从模型中获取数据
        cell.viewModel = viewModel
        return cell
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let viewModel = homeViewModel.viewModelArray[indexPath.row]
        let cellID = getCellIdWithViewmodel(viewModel: viewModel)
        let cell = cellWithID(cellID: cellID)
        //提前
        let  rowHeight = cell.rowHeight(viewModel: viewModel)
        return rowHeight
        
    }

    //计算高度不能够通过从缓冲池获取cell的方式
    //自己从nib中读取cell对象的方式 和可重用的cell没有任何关系
     private func cellWithID(cellID : String) -> HJStatusCell {
        
        let nibName = cellID == originalCellId ? "HJStatusCell" : "HJRetweetedStatus"
        return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).last as! HJStatusCell
    }
    
    //判断使用哪个cell
    private func getCellIdWithViewmodel(viewModel : HJStatusViewModel) -> String {
        if viewModel.status?.retweeted_status == nil {
            
            return originalCellId
        }else {
            return retweetedCellId
        }
    }
    
    
    //将要显示最后一个cell的时候执行静默加载
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.row == homeViewModel.viewModelArray.count - 2 && indicatorView.isAnimating == false {
            indicatorView.startAnimating()
            print("执行静默加载")
            
             loadData()
        }
    }
    
    
}












